package com.wodogs.recharge;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wodogs.recharge.battlenet.BattlenetManage;
import com.wodogs.recharge.battlenet.BattlenetRunnable;
import com.wodogs.recharge.entity.UserAccount;
import com.wodogs.utils.BaseProcess;

@Component
public class BattlenetProcess extends BaseProcess{
	private Logger logger = Logger.getLogger(this.getClass().getName());  
	
	@Autowired
	private BaseService service;
	
	@Override
	public String getWeb_site(){
		return BattlenetManage.WEB_SITE;
	}
	
	private List<UserAccount> listAccount;
	
	public static void main(String[] args) throws InterruptedException {
		
		BattlenetProcess battlenet = new BattlenetProcess();
		battlenet.setWeb_site(BattlenetManage.WEB_SITE);
		
		battlenet.go();
	}

	@Override
	public BattlenetRunnable getRunnable(){
		BattlenetRunnable t1 = new BattlenetRunnable();
		t1.setListData(listData);
		t1.setManage(new BattlenetManage());
		t1.setLogin_url(BattlenetManage.LOGIN_URL);
		return t1;
	}
	
	@Override
	public void go() throws InterruptedException{
		start();//开始
		
		List<UserAccount> listAccount = service.getUndoList(getWeb_site());
		
		if(listAccount == null || listAccount.size()<1){
			logger.info("没有需要执行的账号");
			return;
		}
		logger.info(web_site+" recharge threads start");
		
		//根据用户id判断是否是一个用户冲多次，如果是的就扔一个连接进去
		Map<String,List<UserAccount>> map = new HashMap<>();
		for(UserAccount account:listAccount){
			List<UserAccount> list= map.get(account.getAccount());
			if(list !=null ){
				list.add(account);
				continue;
			}
			list = new ArrayList<>();
			list.add(account);
			map.put(account.getAccount(), list);
		}
		for(List<UserAccount> list : map.values()){
			if(list == null || list.size()<1){
				continue;
			}
			BattlenetRunnable r = getRunnable();
			r.setLogin_url(list.get(0).getUrl());
			r.setAccountList(list);
			r.setManage(new BattlenetManage());
			
			Thread t = new Thread(r);//创建线程
			t.start();
		}
        
	}

	public List<UserAccount> getListAccount() {
		return listAccount;
	}

	public void setListAccount(List<UserAccount> listAccount) {
		this.listAccount = listAccount;
	}
}